package com.ycl.javacore.exam.limit;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * User: OF1089 杨成龙
 * Date: 2019/3/26
 * Time: 2:27 PM
 * Desc: 显示每秒限流10次，主要利用定时器控制每秒，再利用AtomicInteger去实现原子增加
 */
public class LimitPerSecond {

    private long startTime;

    private int limit;//限制多少次

    private int seconds;//多少秒

    public void setStartTime(long startTime) {
        this.startTime = startTime;
    }

    LimitPerSecond(int seconds, int limit) {
        this.seconds = seconds;
        this.limit = limit;
    }

    private static AtomicInteger reqTimes = new AtomicInteger(0);

    public void bizMethod() throws InterruptedException {
        if (System.currentTimeMillis() <= (startTime + seconds * 1000) && reqTimes.incrementAndGet() <= limit) {
            System.out.println(Thread.currentThread().getName() + "执行业务逻辑");
            Thread.sleep(200);
        } else {
            System.out.println(Thread.currentThread().getName() + "被拒绝");
        }
    }

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();

        LimitPerSecond limitPerSecond = new LimitPerSecond(1, 10);
        limitPerSecond.setStartTime(startTime);

        Timer t = new Timer();
        t.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                limitPerSecond.setStartTime(System.currentTimeMillis());
                reqTimes.getAndSet(0);
            }
        }, 1000, 1000);

        for (int i = 0; i < 1000; i++) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            new Thread(() -> {
                try {
                    limitPerSecond.bizMethod();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
